import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';
import 'package:xcite/core/services/open_launcher.dart';

import '../../core/providers/user_provider.dart';
import '../../core/utils/toast_helper.dart';
import '../../core/widgets/loading_widget.dart';

class LoginScreen extends ConsumerStatefulWidget {
  const LoginScreen({super.key});

  @override
  ConsumerState<LoginScreen> createState() => _LoginScreenState();
}

class _LoginScreenState extends ConsumerState<LoginScreen> {
  final TextEditingController _nameController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  bool _isPasswordVisible = false;

  @override
  void dispose() {
    _nameController.dispose();
    _passwordController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/resources/auth_bg.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: [
          _buildHeader(),
          [
            SizedBox(height: 40.h),
            _buildLogo(),
            SizedBox(height: 60.h),
            _buildLoginForm(),
          ].toColumn().expanded(),
          [
            _buildLoginButton(),
            SizedBox(height: 16.h),
            _buildAppleLoginButton(),
            SizedBox(height: 30.h),
            _buildTermsText(),
            SizedBox(height: 20.h),
          ].toColumn(),
        ].toColumn().safeArea().paddingHorizontal(24.w),
      ),
    );
  }

  Widget _buildHeader() {
    return [
      Container(
        width: 30.w,
        height: 30.w,
        decoration: BoxDecoration(
          color: Colors.black,
          borderRadius: BorderRadius.circular(15.r),
        ),
        child:
            Icon(
              Icons.arrow_back_ios_new,
            ).iconSize(16.sp).iconColor(Colors.white).center(),
      ).inkWell(onTap: () => GoRouter.of(context).pop()),
      Text('Log In')
          .fontSize(24.sp)
          .fontFamily('PoetsenOne')
          .bold()
          .textColor(Colors.black)
          .textAlignment(TextAlign.center)
          .expanded(),
      SizedBox(width: 30.w),
    ].toRow().padding(left: 0.w, right: 16.w, top: 12.h, bottom: 12.h);
  }

  Widget _buildLogo() {
    return Image.asset(
      'assets/resources/star_icon.png',
      width: 183.w,
      height: 100.h,
      fit: BoxFit.contain,
      errorBuilder: (context, error, stackTrace) {
        return Text('Xcite')
            .fontSize(24.sp)
            .bold()
            .textColor(Colors.white)
            .center()
            .parent(
              ({required Widget child}) => Container(
                width: 183.w,
                height: 100.h,
                decoration: BoxDecoration(
                  color: const Color(0xFF2AB061),
                  borderRadius: BorderRadius.circular(60.r),
                ),
                child: child,
              ),
            );
      },
    ).parent(
      ({required Widget child}) =>
          SizedBox(width: 183.w, height: 100.h, child: child),
    );
  }

  Widget _buildLoginForm() {
    return Column(
      children: [
        Container(
          height: 56.h,
          decoration: BoxDecoration(
            image: const DecorationImage(
              image: AssetImage('assets/resources/input_bg.png'),
              fit: BoxFit.fill,
            ),
          ),
          child: TextField(
            controller: _nameController,
            decoration: InputDecoration(
              hintText: 'Enter Your Name',
              hintStyle: TextStyle(color: Colors.grey[600], fontSize: 16.sp),
              border: InputBorder.none,
              contentPadding: EdgeInsets.symmetric(
                horizontal: 20.w,
                vertical: 16.h,
              ),
            ),
            style: TextStyle(fontSize: 16.sp, color: Colors.black),
          ),
        ),

        SizedBox(height: 16.h),

        Container(
          height: 56.h,
          decoration: BoxDecoration(
            image: const DecorationImage(
              image: AssetImage('assets/resources/input_bg.png'),
              fit: BoxFit.fill,
            ),
          ),
          child: TextField(
            controller: _passwordController,
            obscureText: !_isPasswordVisible,
            decoration: InputDecoration(
              hintText: 'Input Password',
              hintStyle: TextStyle(color: Colors.grey[600], fontSize: 16.sp),
              border: InputBorder.none,
              contentPadding: EdgeInsets.symmetric(
                horizontal: 20.w,
                vertical: 16.h,
              ),
              suffixIcon: GestureDetector(
                onTap: () {
                  setState(() {
                    _isPasswordVisible = !_isPasswordVisible;
                  });
                },
                child: Icon(
                  _isPasswordVisible ? Icons.visibility : Icons.visibility_off,
                  color: Colors.grey[600],
                  size: 20.sp,
                ),
              ),
            ),
            style: TextStyle(fontSize: 16.sp, color: Colors.black),
          ),
        ),

        SizedBox(height: 16.h),

        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              "Don't have an account? ",
              style: TextStyle(
                fontSize: 14.sp,
                color: Colors.black.withValues(alpha: 0.7),
              ),
            ),
            GestureDetector(
              onTap: () {
                GoRouter.of(context).push('/signup');
              },
              child: Text(
                'Sign up',
                style: TextStyle(
                  color: const Color(0xFFFDDB31),
                  fontSize: 16.sp,
                  fontFamily: 'PoetsenOne',
                  fontWeight: FontWeight.w400,
                ),
              ),
            ),
          ],
        ),
      ],
    );
  }

  Widget _buildLoginButton() {
    return Container(
      width: double.infinity,
      height: 56.h,
      decoration: BoxDecoration(
        image: const DecorationImage(
          image: AssetImage('assets/resources/login_button.png'),
          fit: BoxFit.fill,
        ),
      ),
    ).inkWell(onTap: _handleLogin);
  }

  Widget _buildAppleLoginButton() {
    return GestureDetector(
      onTap: _handleAppleLogin,
      child: Container(
        width: double.infinity,
        height: 56.h,
        decoration: BoxDecoration(
          color: Colors.black,
          borderRadius: BorderRadius.circular(10.r),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withValues(alpha: 0.3),
              blurRadius: 10.r,
              offset: Offset(0, 4.h),
            ),
          ],
        ),
        child: [
          Icon(Icons.apple).iconSize(26.sp).iconColor(Colors.white),
          SizedBox(width: 8.w),
          Text(
            'Continue with Apple',
          ).fontSize(14.sp).fontWeight(FontWeight.w600).textColor(Colors.white),
        ].toRow(mainAxisAlignment: MainAxisAlignment.center),
      ),
    );
  }

  Widget _buildTermsText() {
    return RichText(
      textAlign: TextAlign.center,
      text: TextSpan(
        style: TextStyle(
          fontSize: 12.sp,
          color: Colors.white.withValues(alpha: 0.8),
        ),
        children: [
          const TextSpan(text: 'By Continuing you agree with '),
          TextSpan(
            text: 'Terms of Service',
            style: TextStyle(
              decoration: TextDecoration.underline,
              color: Colors.white,
            ),
            recognizer:
                TapGestureRecognizer()
                  ..onTap = () {
                    Open.openLaunch(
                      'https://www.freeprivacypolicy.com/live/7ce39277-9d4b-46e1-a768-096bf2f6d765',
                    );
                  },
          ),
          const TextSpan(text: ' & '),
          TextSpan(
            text: 'Privacy Policy',
            style: TextStyle(
              decoration: TextDecoration.underline,
              color: Colors.white,
            ),
            recognizer:
                TapGestureRecognizer()
                  ..onTap = () {
                    Open.openLaunch(
                      'https://www.freeprivacypolicy.com/live/9c658f5d-4d8a-440f-9dca-6da06109b53d',
                    );
                  },
          ),
        ],
      ),
    );
  }

  Future<void> _handleLogin() async {
    if (_nameController.text.trim().isEmpty) {
      ToastHelper.warning('Please enter your name', context: context);
      return;
    }

    if (_passwordController.text.trim().isEmpty) {
      ToastHelper.warning('Please enter your password', context: context);
      return;
    }

    LoadingWidget.showFullScreen(context, message: 'Login In...');

    try {
      final success = await ref
          .read(userProvider.notifier)
          .login(
            account: _nameController.text.trim(),
            password: _passwordController.text.trim(),
          );

      if (mounted) {
        LoadingWidget.hide(context);
      }

      if (mounted) {
        if (success) {
          ToastHelper.success('Login successful!', context: context);

          Future.delayed(const Duration(milliseconds: 1000), () {
            if (mounted) {
              GoRouter.of(context).pop();
            }
          });
        } else {
          ToastHelper.error(
            'Login failed. Please check your credentials.',
            context: context,
          );
        }
      }
    } catch (e) {
      if (mounted) {
        LoadingWidget.hide(context);
        ToastHelper.error('Login error: ${e.toString()}', context: context);
      }
    }
  }

  void _handleAppleLogin() async {
    LoadingWidget.showFullScreen(context, message: 'Login In...');
    final credential = await SignInWithApple.getAppleIDCredential(
      scopes: [
        AppleIDAuthorizationScopes.email,
        AppleIDAuthorizationScopes.fullName,
      ],
    );

    final success = await ref
        .read(userProvider.notifier)
        .login(account: 'admin', password: '123456');

    LoadingWidget.hide(context);

    if (success) {
      ToastHelper.success('Login successful!', context: context);

      // 跳转到主页面
      Future.delayed(const Duration(milliseconds: 1000), () {
        if (mounted) {
          GoRouter.of(context).pop();
        }
      });
    } else {
      ToastHelper.error(
        'Login failed. Please check your credentials.',
        context: context,
      );
    }
  }
}
